package com.itany.cloud.controller;

import com.itany.cloud.entity.User;
import com.itany.cloud.service.UserService;
import com.itany.cloud.util.ResponseResult;
import io.swagger.v3.oas.annotations.Hidden;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Parameters;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @author 石小俊
 */
@RestController
@RequestMapping("/users")
@Tag(name = "用户微服务模块", description = "用户功能对应的微服务模块,可以实现用户的CURD操作")
public class UserController {

    @Autowired
    private UserService userService;

    @Value("${server.port}")
    private String serverPort;

    @Operation(summary = "根据主键查询", description = "根据主键查询指定的用户信息")
    @Parameter(name = "id", description = "主键字段", required = true)
    @GetMapping("/{id}")
    public ResponseResult findById(@PathVariable Integer id) {
        System.out.println("正在访问" + serverPort + "端口的服务");
        // 模拟响应超时的请求
        if (id == 1) {
            try {
                Thread.sleep(500);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }
        User user = userService.findById(id);
        return ResponseResult.success(user);
    }

    @Operation(summary = "查询所有")
    @GetMapping
    public ResponseResult findAll() {
        List<User> users = userService.findAll();
        return ResponseResult.success("我是" + serverPort + "端口的服务", users);
    }

    @Operation(summary = "添加")
    @Parameters({
            @Parameter(name = "username", description = "用户名"),
            @Parameter(name = "password", description = "密码")
    })
    @PostMapping
    public ResponseResult addUser(User user) {
        userService.addUser(user);
        return ResponseResult.success();
    }

    @Operation(summary = "修改")
    @Parameter(name = "user", description = "用户对象")
    @PutMapping
    public ResponseResult modifyUser(User user) {
        userService.modifyUser(user);
        return ResponseResult.success();
    }

    @Hidden
    @Operation(summary = "删除")
    @DeleteMapping("/{id}")
    @Parameter(name = "id", description = "主键字段")
    public ResponseResult deleteById(@PathVariable Integer id) {
        userService.deleteById(id);
        return ResponseResult.success();
    }
}
